const paramsObj = require('./params.js');
const fs = require('fs');//引入文件处理模块
const path = require('path');//引入路径核心模块
const os = require('os');//引入os核心模块 用于获取本机IP

// 获取项目根目录
function getProjectRoot(dir) {
  return path.resolve(__dirname, '../', dir)
};

//获取url路径
const data = fs.readFileSync(getProjectRoot('config/测试.js'), 'utf8');
let firstIndex = data.indexOf('`');
let secondIndex = data.indexOf('`', firstIndex + 1);
let res = data.substring(firstIndex, secondIndex + 1);
let obj = JSON.parse(res.replace(/`/gi, ''));
let url = '';
obj.data.forEach(item => {
  if (item.name == "URL") {
    url = item.value
  }
});

// 获取本机IP
function getIPAdress() {
  var interfaces = os.networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
};

// 获取入口和HtmlWebpackPlugin配置
const NODE_ENV = process.env.NODE_ENV;//获取package.json中配置的环境
let entry = {};//定义入口对象
let htmlArray = [];//定义HtmlWebpackPlugin配置数组
function getEntryAndGetHtmlWebpackPluginParams() {
  let fileArr = fs.readdirSync(getProjectRoot('src/pages'));//获取pages子文件夹组成的数组
  fileArr.forEach(item => {//遍历文件数组
    let fileIndoorArr = fs.readdirSync(getProjectRoot(`src/pages/${item}`));//获取文件数组中的子文件组成的数组
    fileIndoorArr.forEach(val => {//遍历
      let extname = path.extname(val);//获取后缀名
      if (extname == '.js') {//如果是js文件
        entry[item] = getProjectRoot(`src/pages/${item}/${val}`);
      } else if (extname == '.html') {//如果是html文件
        if (item == paramsObj.indexHtml) {//如果是home文件
          htmlArray.push({
            // filename: val,
            filename: 'index.html',
            template: getProjectRoot(`src/pages/${item}/${val}`),
            inject: true,
            chunks: [item],
            minify: NODE_ENV == 'development' ? false : {
              removeComments: true,
              collapseWhitespace: true,
              removeAttributeQuotes: true
            }
          })
        } else {//如果是非home文件
          htmlArray.push({
            filename: `pages/${item}/${val}`,
            template: getProjectRoot(`src/pages/${item}/${val}`),
            inject: true,
            chunks: [item],
            minify: NODE_ENV == 'development' ? false : {
              removeComments: true,
              collapseWhitespace: true,
              removeAttributeQuotes: true
            }
          })
        }
      }
    })
  });
};
getEntryAndGetHtmlWebpackPluginParams();

module.exports = {
  entry,
  htmlArray,
  url,

  getProjectRoot,
  getIPAdress,
}